<!--
 * @Author: zt0233
 * @Date: 2022-02-28 16:16:42
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-10-25 09:18:22
 * @FilePath: \web-pc\src\pages\big-screen\view\indexs\left-center.vue
-->
<template>
  <Echart id="leftCenter" :options="options" class="left_center_inner" v-if="pageflag" ref="charts" />
  <Reacquire v-else @onclick="getData" style="line-height:200px">
    重新获取
  </Reacquire>
</template>

<script>
import { currentGET } from 'api/modules'
// 导入模拟数据
import userOverviewData from '@/mock/mockData.js'
export default {
  data() {
    return {
      options: {},
      countUserNumData: {
        lockNum: 0,
        onlineNum: 0,
        offlineNum: 0,
        totalNum: 0
      },
      pageflag: true,
      timer: null,
      requestCount: 0 // 请求计数器，用于调试
    };
  },
  created() {
    console.log('left-center组件创建');
  },
  mounted() {
    console.log('left-center组件挂载，开始获取数据');
    // 组件挂载后获取数据，确保DOM已经准备好
    this.$nextTick(() => {
      this.getData();
    });
  },
  beforeDestroy() {
    console.log('left-center组件即将销毁，清理资源');
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    
    // 清除图表实例
    if (this.myChart) {
      this.myChart.dispose();
      this.myChart = null;
    }
    
    // 移除事件监听
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    clearData() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    getData() {
      this.pageflag = true;
      
      this.requestCount++;
      console.log(`开始获取用户总览数据...(请求次数: ${this.requestCount})`);

      // 直接使用导入的模拟数据
      const res = userOverviewData;
      console.log(`用户总览数据响应 (请求次数: ${this.requestCount}):`, res);
      
      if (res && res.success) {
        console.log('用户总览数据获取成功:', res.data);
        this.countUserNumData = res.data;
        this.$nextTick(() => {
          this.init();
          
          // 只在第一次成功获取数据后启动轮询
          if (this.requestCount === 1) {
            console.log('首次数据获取成功，启动轮询');
            this.switper();
          }
        });
      } else {
        console.error('用户总览数据获取失败:', res);
        this.pageflag = false;
        this.$Message({
          text: res && res.msg ? res.msg : '获取数据失败',
          type: 'warning'
        });
      }
    },
    },
    //轮询
    switper() {
      console.log('启动用户总览数据轮询...');
      
      // 获取轮询间隔时间
      const interval = (this.$store.state.setting && this.$store.state.setting.echartsAutoTime) || 30000;
      console.log(`轮询间隔: ${interval}ms`);
      
      // 清除可能存在的旧定时器
      if (this.timer) {
        console.log('清除旧的轮询定时器');
        clearInterval(this.timer);
        this.timer = null;
      }
      
      // 轮询函数 - 模拟数据变化
      let looper = () => {
        console.log('执行数据轮询 - 模拟数据变化');
        // 生成随机因子，模拟数据变化
        const randomFactor = Math.random() * 0.2 + 0.9; // 0.9-1.1的随机因子
        
        // 创建新的数据对象，避免直接修改原始数据
        const newData = {
          success: true,
          data: {
            lockNum: Math.floor(userOverviewData.data.lockNum * randomFactor),
            onlineNum: Math.floor(userOverviewData.data.onlineNum * randomFactor),
            offlineNum: Math.floor(userOverviewData.data.offlineNum * randomFactor),
            totalNum: Math.floor(userOverviewData.data.totalNum * randomFactor)
          }
        };
        
        // 更新数据并重新渲染图表
        this.countUserNumData = newData.data;
        this.init();
      };
      
      // 设置定时器
      this.timer = setInterval(looper, interval);
      
      // 确保图表实例存在
      if (this.$refs.charts && this.$refs.charts.chart) {
        let myChart = this.$refs.charts.chart;
        
        // 移除可能存在的旧事件处理器
        myChart.off('mouseover');
        myChart.off('mouseout');
        
        // 鼠标悬停时暂停轮询
        myChart.on('mouseover', params => {
          console.log('鼠标悬停，暂停轮询');
          this.clearData();
        });
        
        // 鼠标移出时恢复轮询
        myChart.on('mouseout', params => {
          console.log('鼠标移出，恢复轮询');
          if (!this.timer) {
            console.log('重新启动轮询定时器');
            this.timer = setInterval(looper, interval);
          }
        });
      } else {
        console.warn('图表实例不存在，无法设置鼠标事件');
      }
    },
    init() {
      console.log('初始化用户总览图表，数据:', this.countUserNumData);
      
      // 确保数据存在
      if (!this.countUserNumData || typeof this.countUserNumData !== 'object') {
        console.error('用户总览数据无效:', this.countUserNumData);
        this.pageflag = false;
        return;
      }
      
      // 确保数据字段存在且为数字
      const lockNum = parseInt(this.countUserNumData.lockNum) || 0;
      const onlineNum = parseInt(this.countUserNumData.onlineNum) || 0;
      const offlineNum = parseInt(this.countUserNumData.offlineNum) || 0;
      const total = parseInt(this.countUserNumData.totalNum) || 0;
      
      console.log('处理后的数据:', { lockNum, onlineNum, offlineNum, total });
      
      let colors = ["#ECA444", "#33A1DB", "#56B557"];
      let piedata = {
        name: "用户总览",
        type: "pie",
        radius: ["42%", "65%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderColor: "rgba(0,0,0,0)",
          borderWidth: 2,
        },

        color: colors,
        data: [
          // {
          //   value: 0,
          //   name: "告警",
          //   label: {
          //     shadowColor: colors[0],
          //   },
          // },
          {
            value: lockNum,
            name: "锁定",
            label: {
              shadowColor: colors[0],
            },
          },
          {
            value: onlineNum,
            name: "在线",
            label: {
              shadowColor: colors[2],
            },
          },
          {
            value: offlineNum,
            name: "离线",
            label: {
              shadowColor: colors[1],
            },
          },


        ],
      };
      this.options = {
        title: {
          // zlevel: 0,
          text: ["{value|" + total + "}", "{name|总数}"].join("\n"),
          top: "center",
          left: "center",
          textStyle: {
            rich: {
              value: {
                color: "#ffffff",
                fontSize: 24,
                fontWeight: "bold",
                lineHeight: 20,
              },
              name: {
                color: "#ffffff",
                lineHeight: 20,
              },
            },
          },
        },
        tooltip: {
          trigger: "item",
          backgroundColor: "rgba(0,0,0,.6)",
          borderColor: "rgba(147, 235, 248, .8)",
          textStyle: {
            color: "#FFF",
          },
        },
        legend: {
          show: false,
          top: "5%",
          left: "center",
        },
        series: [
          //展示圆点
          {
            ...piedata,
            tooltip: { show: true },
            label: {
              formatter: "   {b|{b}}   \n   {c|{c}个}   {per|{d}%}  ",
              //   position: "outside",
              rich: {
                b: {
                  color: "#fff",
                  fontSize: 12,
                  lineHeight: 26,
                },
                c: {
                  color: "#31ABE3",
                  fontSize: 14,
                },
                per: {
                  color: "#31ABE3",
                  fontSize: 14,
                },
              },
            },
            labelLine: {
              length: 20, // 第一段线 长度
              length2: 36, // 第二段线 长度
              show: true,
              emphasis: {
                show: true
              }
            },
          },
          {
            ...piedata,
            tooltip: { show: true },
            itemStyle: {},
            label: {
              backgroundColor: "inherit", //圆点颜色，auto：映射的系列色
              height: 0,
              width: 0,
              lineHeight: 0,
              borderRadius: 2.5,
              shadowBlur: 8,
              shadowColor: "auto",
              padding: [2.5, -2.5, 2.5, -2.5],
            },
            labelLine: {
              length: 20, // 第一段线 长度
              length2: 36, // 第二段线 长度
              show: false,
            },
          },
        ],
      };
  },
};
</script>
<style lang='scss' scoped>
</style>